/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   14-7-29 下午1:56 Created by dwzhang
 */
package com.jade.framework.base.comm.netty;

import com.jade.framework.base.comm.CommEndpoint;
import com.jade.framework.base.comm.ProtocolHandler;
import com.jade.framework.base.comm.ProtocolSession;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 连接长时间空闲的处理器。
 *
 * @author dwzhang
 * @version 1.0 14-7-29 下午1:56
 */
public class NettyIdleHandler
        extends ChannelInboundHandlerAdapter
{
    protected CommEndpoint<Channel> endpoint;

    public NettyIdleHandler(CommEndpoint<Channel> endpoint)
    {
        this.endpoint = endpoint;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception
    {
        ProtocolSession session = endpoint.getSession(ctx.channel());
        if (session != null) {
            ProtocolHandler handler = session.getProtocol().getProtocolHandler();
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state().equals(IdleState.ALL_IDLE) && handler != null) {
                    handler.idle(session);
                }
            }
        }
    }
}
